package com.ruoyi.web.controller.tool.designpattern.behavioralPatterns.observer;

/**
 * TODO
 *
 * @author Hack2003
 * @date 2024/3/20 14:55
 **/
import java.util.ArrayList;
import java.util.List;

// 主题接口
interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers(Event event);
}

// 具体主题
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();

    public void setState(int state) {
        notifyObservers(new Event(state));
    }

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void notifyObservers(Event event) {
        for (Observer observer : observers) {
            observer.update(event);
        }
    }
}

//定义事件
class Event {
    private int state;

    public int getState() {
        return state;
    }

    public Event(int state) {
        this.state = state;
    }
}
// 观察者接口
interface Observer {
    void update(Event event);
}

// 具体观察者
class ConcreteObserver implements Observer {
    private String tag;
    public ConcreteObserver(String tag){
        this.tag = tag;
    }
    @Override
    public void update(Event event) {
        System.out.println(tag+"Received state update: " + event.getState());
    }
}

/**
 * 观察者模式（当主题状态发生变化时，会通知所有注册的观察者对象。）
 */
public class Test {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
        ConcreteObserver observer1 = new ConcreteObserver("A用户");
        ConcreteObserver observer2 = new ConcreteObserver("B用户");

        subject.registerObserver(observer1);
        subject.registerObserver(observer2);

        subject.setState(1);
        subject.removeObserver(observer1);
        subject.setState(2);
    }
}